package com.zmis.model.user.action;

import java.io.Serializable;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.zmis.core.QueryResult;
import com.zmis.core.action.GenericAction;
import com.zmis.model.user.User;
import com.zmis.model.user.dao.UserDao;
import com.zmis.utils.StringUtil;

@Controller("model/user/login")
@Scope("prototype")
public class LoginAction extends GenericAction implements Serializable {
	private static final long serialVersionUID = 1L;
	private User user;
	
	@Resource(name="userDaoImpl")
	private UserDao userDao;
	@Override
	public String execute() throws Exception {
		
		this.setRequest(ServletActionContext.getRequest());
		HttpSession session = request.getSession();
		String zcode = request.getParameter("zcode");
		//获取session中的验证码
		String sessionZcode = (String) session.getAttribute(com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
		if(!sessionZcode.equals(zcode)) {//验证码比较
			this.setMessage("验证码输入错误!");
			return "input";
		}else {
			if(StringUtil.isNotEmpty(user.getUserName()) && StringUtil.isNotEmpty(user.getUserPwd())) {
				QueryResult<User> users= userDao.getData(User.class, "o.userName=?1 and o.userPwd=?2", new Object[]{user.getUserName(), user.getUserPwd()});
				long count = users.getCount();
				if(count==1) {
					this.setMessage("登录成功");
					session.setAttribute("user", users.getResultList());
					return SUCCESS;
				}else {
					this.setMessage("不存在用户，或密码输入错误");
					return "input";
				}
			}else {
				this.setMessage("用户名和密码都不能为空");
				return "input";
			}
		}
	}
	//TODO 改造：前台登录直接发ajax发送请求  
	//TODO 消息需要封装
	
	//getting/setting
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}

	public UserDao getUserDao() {
		return userDao;
	}
	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	
}
